'''
Created on Mar 16, 2013

@author: Petko
'''
from sent.utils import CommonResult, ErrorIds, find_implementation
from django.http import HttpResponse
import json
from sententialyzer.settings import SENTENTIALYZER_RESULT_PRINTER

class ResultPrinter():
    '''
    classdocs
    '''
    def __init__(self):
        '''
        Constructor
        '''
        pass
    
    def messageFromErrorId(self, errorId):
        errorStr = {
            ErrorIds.UNAUTHORIZED: ' Unauthorized'
        }.get(errorId, 'Unknnown')
        return str(errorId) + errorStr
    
    def printResult(self, commonResult):
        assert isinstance(commonResult, CommonResult)
        raise NotImplementedError('Please implement the method printResult')
    

class JSONResultPrinter(ResultPrinter):
    
    def printResult(self, commonResult):
        assert isinstance(commonResult, CommonResult)
        
        if commonResult.errorId == ErrorIds.SUCCESS:
            if commonResult.totalResults >= 0 and isinstance(commonResult.result, list):
                resultObj = {}
                resultObj['page'] = commonResult.result
                resultObj['totalResults'] = commonResult.totalResults
            else:
                resultObj = commonResult.result
            
            
            resultStr = json.dumps(resultObj)
            return HttpResponse(resultStr, content_type="application/json")
        else:
            resultObj = {'errorCode': commonResult.errorId}
            if isinstance(commonResult.result, basestring):
                resultObj['error_msg'] = commonResult.result
            else:
                resultObj['error_msg'] = self.messageFromErrorId(commonResult.errorId)
            return HttpResponse(json.dumps(resultObj), content_type="application/json", status=commonResult.errorId)


ResultPrinterClass = find_implementation(SENTENTIALYZER_RESULT_PRINTER, ResultPrinter)

g_resultPrinter=ResultPrinterClass()

def getPrinter():
    resultPrinter = g_resultPrinter
    assert isinstance(resultPrinter, ResultPrinter)
    return resultPrinter
